import {EyeOutlined, FallOutlined, SearchOutlined, SyncOutlined} from '@ant-design/icons'
import {useRequest} from '@umijs/hooks'
import {Button, Card, Cascader, DatePicker, Drawer, Form, Input, message, Table, Tag, TreeSelect} from 'antd'
import {Store} from 'rc-field-form/lib/interface'
import React, {useEffect, useState} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import TableToolbar from '../../../../components/TableSetting/TableToolbar'
import {fetchRequest} from '../../../../utils/Request'
import {url} from '../../../../utils/url'
import '../../../DepartmentManage/views/style.css'
import actionTypes from '../../actionTypes'
import '../index.css'
import moment from 'moment'
import AccessRecordDetail from './AccessRecordDetail'
import exportExcel from "@/utils/exportExcel";

interface Detail {
    visible: boolean,
    content: any
}

interface RequestAddres {
    level: number,
    collegeId: string,
    collegeAreaId: string,
    building: string,
    unit: string,
    floor: string
}

interface RequestParams {
    "userName": string,
    "phone": string,
    "beginDate": string,
    "endDate": string,
    "deptId": string,
    "index": number,
    "num": number

}

interface RecordParams {
    collegeAreaId: string,
    beginDate: string,
    endDate: string,
    index: number,
    num: number
    flag?: boolean

}

const {SHOW_PARENT} = TreeSelect;

export default function AccessRecord() {

    const columns = [{
        title: "姓名",
        dataIndex: "studentName",
        key: 'studentName',
        align: 'center' as 'center'
    },
        {
            title: "防疫核验",
            key: 'healthCode',
            render: (record: any) => {
                return <Tag color={(record.healthCode === undefined || record.healthCode === null) ?
                    undefined : record.healthCode.color}>{(record.healthCode === undefined || record.healthCode === null) ? "" :
                    record.healthCode.stateName}</Tag>
            }
        },
        {
            title: "门禁出入",
            dataIndex: "inOutFlag",
            key: 'inOutFlag',
            align: 'center' as 'center',
            // render: (text: string) => text === "1" ? "进入" : text === "2" ? "出" : "--"
            // align: 'center'
        }, {
            title: "开门方式",
            dataIndex: "openType",
            key: 'openType',
            align: 'center' as 'center',
            // render: (record: any) =>
            //     (
            //         record === 2 ? <Popover content="白卡开门">
            //             <IconFont type="icon-menjinqiabanli" style={{ marginRight: '10px' }} className={'cardOpened'} />
            //         </Popover> : record === 3 || record === 5 ? <Popover content="翼卡通开门">
            //             <IconFont type="icon-shoujikaimen" className={'cardOpened'} />
            //         </Popover> : <Popover content="人脸开门">
            //                     <IconFont type="icon-renlian" style={{ marginRight: '10px' }} className={'cardOpened'} />
            //                 </Popover>)

        }, {
            title: "出入时间",
            dataIndex: 'recordTime',
            key: 'recordTime',
            align: 'center' as 'center'
        },
        {
            title: "体温",
            dataIndex: 'temperature',
            key: 'temperature',
            align: 'center' as 'center'
        },
        {
            title: "门禁卡状态",
            dataIndex: 'accessCardState',
            key: "accessCardState",
            align: 'center' as 'center',
            render: (text: string) => {
                return text === '有效' ? <Tag color="#0ec671">{text}</Tag> : <Tag color="#f50">{text}</Tag>
            }
        },
        {
            title: "操作",
            align: 'center' as 'center',
            render: (record: any) => <span onClick={e => e.stopPropagation()}>
            <Tag className="tags-hover" color="#108ee9" icon={<EyeOutlined/>}
                 onClick={() => onRowClick(record)}>查看详情</Tag>
        </span>
        }]


    const [addressNode, setAddressNode] = useState([])

    const OnChange = (value: any, selectedOptions: any) => {

    };
    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const [modifyInfo, setmodifyInfo] = useState<{ visible: boolean, content: any }>({visible: false, content: null})
    const [requestAddress, setRequestAddress] = useState<any>({
        "level": 0,
        "collegeId": "",
        "collegeAreaId": "",
        "building": "",
        "unit": "",
        "floor": ""
    })

    const [RecordParams, setRecordParams] = useState<any>({
        collegeAreaId: "",
        beginDate: "",
        endDate: "",
        index: 1,
        num: 10,
        deptId: '',
    })

    const [form] = Form.useForm()
    const [k, setK] = useState<any>(0);
    const [classValue, setClassValue] = useState<any>('')

    const onChange = (value: any, selectedOptions: any) => {
        if (Array.isArray(selectedOptions)) {
            setClassValue(selectedOptions[selectedOptions.length - 1]?.value ?? '')
        } else {
            setClassValue('')
        }
    }


    async function getAllAdd(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                return json.data
            } else {
                return []
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    //点击搜索按钮
    function handleFinish(values: Store) {

        setRecordParams({
            deptId: classValue,
            collegeAreaId: typeof values.allAddress === "undefined" ? "" : values.allAddress[1],
            beginDate: typeof values.date === "undefined" ? "" : moment(values.date[0]).format("YYYY-MM-DD 00:00:00"),
            endDate: typeof values.date === "undefined" ? "" : moment(values.date[1]).format("YYYY-MM-DD 23:59:59"),
            index: 1,
            num: 10,
            flag: true,
            studentName: values.studentName

        })
    }

    //点击重置按钮
    function handleReset() {
        form.resetFields();
        setClassValue('');
        setRecordParams({collegeAreaId: "", beginDate: "", endDate: "", index: 1, num: 10})
    }


    const getAllAddress1 = useRequest(getAllAddressNode1, {
        manual: true,
        loadingDelay: 200
    })

    async function getAllAddressNode1(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                // console.log('getAllAddressNode:',json)
                setAddressNode(json.data)
                // return json.data
            } else {
                // console.log('getAllAddressNode:',json)
                // return []
            }
        } catch (error: any) {
            // console.log('getAllAddressNode:',error)
        }
    }

    //获取redux中的tableData
    const tableData = useSelector((state: any) => {
        // console.log(state.entranceManage.entranceManage)
        return state.entranceManage.accessRecord
    })
    const tableDataDetail = useSelector((state: any) => {
        return state.entranceManage.ACCESS_RECORD_DETAIL
    })

    const exportClick = async () => {
        if (!RecordParams.flag) {
            message.error('请点击查询')
            return
        }
        const {success, accessRecordsTableDownload, error} = await fetchRequest(url.GET_ACCESS_DOWNLOAD, RecordParams)

        if (success) {

            const temp = accessRecordsTableDownload.map((item: any) => {

                return {
                    '姓名': item.studentName,
                    '组织机构': item.deptName,
                    '门禁出入': item.inOutFlag,
                    '开门方式': item.openType,
                    '门禁卡状态': item.accessCardState,
                    '出入时间': item.recordTime,
                    '体温': item.temperature,

                }
            })
            exportExcel(temp, `${RecordParams.beginDate}~${RecordParams.endDate}进出记录.xlsx`)
        } else {
            message.error(error)
        }


    }

    const [treeNode, setTreeNode] = useState<any>([]);
    const [requestParamTree, setRequestParamTree] = useState<any>(
        {
            "level": 0,
            "treeId": "0"
        }
    );

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: any) {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);

            console.log(json)
            if (json.success) {
                message.destroy();


                const list = json.data.map((item: any) => {
                    let temp
                    delete item.children;

                    temp = {...item, pId: item.parentId, id: item.treeId}
                    return temp
                });

                if (params.level === 0) {
                    setTreeNode(list);
                }

                return list


            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)

        }

    }

    const loadData = async (selectedOptions: any) => {

        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;


        const id = setTimeout(async () => {
            targetOption.loading = false;
            targetOption.children = await getSchoolOrganizationRequest({
                treeId: targetOption.treeId,
                level: targetOption.level + 1
            })
            setTreeNode([...treeNode])

            clearTimeout(id)
        })


    };

    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree])

    const tProps = {
        options: treeNode,
        loadData,
        onChange,
        changeOnSelect: true,
        placeholder: '请选择班级范围',

        style: {
            width: '100%',
        },
    }

    function filter(inputValue: any, path: any) {
        return path.some((option: any) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    //查询框
    const searchForm = (
        <Card className="search-form"> <Form form={form} layout="inline" initialValues={{healthState: -1}}
                                             onFinish={handleFinish} onReset={handleReset}>

            <Form.Item className="form-control-item" name="allAddress" label="组织机构">
                <Cascader  {...tProps} placeholder={'请选择组织机构'} showSearch={{filter}} style={{width: 400}}/>
            </Form.Item>


            <Form.Item className="form-control-item" name="date" label="进出时间">
                <DatePicker.RangePicker/>
            </Form.Item>

            <Form.Item className="form-control-item" name="studentName" label="姓名">
                <Input/>
            </Form.Item>

            <Form.Item className="form-control-item">
                <Button key="1" type="primary" icon={<SearchOutlined/>} htmlType="submit"
                        style={{marginRight: '8px'}}>搜索</Button>
                <Button key="2" icon={<SyncOutlined/>} htmlType="reset">重置</Button>
                <Button key="3" icon={<FallOutlined/>} onClick={exportClick} className={'daichu'}>导出</Button>


            </Form.Item>

        </Form></Card>)

    // const data = [{}]


    const [detail, setDetail] = useState<Detail>({visible: false, content: null})


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])

    //监听请求参数的变化 变化之后进行请求
    useEffect(() => {
        getAllAddress1.run(requestAddress)
    }, [requestAddress])


    //点击行的时候
    function onRowClick(value: any) {
        setDetail({visible: true, content: Number(value.accessRecordsId)})
    }

    //当列设置改变的时候
    function onColumnsChange(checkedList: any[]) {
        // console.log(checkedList)
        setcolumnsKey(checkedList)
    }


    //活的门禁人员信息管理的table
    const getAccess = useRequest(getAccessInfo, {
        loadingDelay: 200,
        manual: true
    })


    //监听请求参数的变化 变化之后进行请求
    useEffect(() => {
        getAccess.run(RecordParams)
    }, [RecordParams])


    //递归修改item的key
    function disableSelect(arr: any[],) {
        arr.map(item => {
            delete item.disabled
            item.key = item.deptID
            item.value = item.deptID
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }


    const dispatch = useDispatch();

    //异步请求的接口
    async function getAccessInfo(params: RecordParams) {
        try {
            const json = await fetchRequest(url.GET_ACCESS_RECORD, params);
            if (json.success) {
                dispatch({type: actionTypes.GET_ACCESS_RECORD, payload: {data: json.data.rows, total: json.data.total}})
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    ///

    //点击刷新按钮
    function onRefresh() {
        getAccess.run(RecordParams)
    }

    function onClose() {
        setDetail({...detail, visible: false});
    }


    //点击分页的时候
    function handlePageChange(page: number) {
        setRecordParams({
            ...RecordParams,
            index: page
        })
    }


    return (
        <div>
            {searchForm}
            <Card className="search-form-table">


                <TableToolbar tableName="进出记录表" columns={columns} onColumnsChange={onColumnsChange}
                              onRefresh={onRefresh} onAdd={false}/>
                <Table
                    loading={getAccess.loading}
                    pagination={{
                        hideOnSinglePage: true,
                        simple: true,
                        onChange: handlePageChange,
                        current: RecordParams.index,
                        showSizeChanger: false,
                        total: tableData.total
                    }} rowKey={(record: any) => record.accessRecordsId}
                    columns={realColumns} dataSource={tableData.data}/>

            </Card>
            <Drawer width="70%" destroyOnClose visible={detail.visible} onClose={onClose} title="详细信息">
                <AccessRecordDetail content={detail.content} onClose={onClose}/>
            </Drawer>


        </div>
    )
}
